package org.budo.poi.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.poi.ss.usermodel.Row;
import org.budo.support.lang.util.ListUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public abstract class AbstractRowAppender implements RowAppender {
    private List<String> titles = new ArrayList<String>();

    private Integer columnFrom = 0;

    @Override
    public void appendTitle(Row titleRow) {
        for (int i = 0; i < this.titles.size(); i++) {
            titleRow.createCell(this.columnFrom + i) //
                    .setCellValue(this.titles.get(i));
        }
    }

    protected void appendMap(Row row, Map<String, Object> map, Integer columnFrom) {
        this.columnFrom = columnFrom; // 固定的列的数量

        if (null == map) {
            log.error("#17 appendMap, row=" + row + ", map=" + map + ", columnFrom=" + columnFrom);
            return;
        }

        for (Entry<String, Object> entry : map.entrySet()) {
            Integer index = ListUtil.findIndex(this.titles, entry.getKey()); // 这个列是第几列
            if (null == index) {
                this.titles.add(entry.getKey());
                index = this.titles.size() - 1; // 初次出现的列
            }

            Object value = entry.getValue();
            String cellValue = null == value ? "" : value.toString();

            row.createCell(columnFrom + index) //
                    .setCellValue(cellValue);
        }
    }
}
